﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.UserCommand;
using MD5Hash;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.UserHandler
{
    public class UpdPassUserHandler : IRequestHandler<UpdPassUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IMapper mapper;
        private readonly ILogger<UpdPassUserHandler> logger;

        public UpdPassUserHandler(IBaseRepository<User> userRep, IMapper mapper, ILogger<UpdPassUserHandler> logger)
        {
            this.userRep = userRep;
            this.mapper = mapper;
            this.logger = logger;
        }

        public Task<APIResult<object>> Handle(UpdPassUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                var model=userRep.GetAll().FirstOrDefault(x=>x.UserId==request.UserId);
                model.Pass = request.Pass.GetMD5();
                var s=userRep.Update(model).Result;
                if (s > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "修改密码成功";
                    result.Data = s;
                    logger.LogInformation($"{model.Name}修改密码成功");
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "修改密码失败";
                    result.Data = s;
                    logger.LogError($"{model.Name}修改密码失败");
                }
                return Task.FromResult( result );
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
